# jq(1) completion                                         -*- shell-script -*-

_jq()
{
    local cur prev words cword
    _init_completion || return

    case $prev in
        --help | --version | --arg | --argjson | --slurpfile | --argfile)
            return
            ;;
        --indent)
            COMPREPLY=($(compgen -W '{1..8}' -- "$cur"))
            return
            ;;
        --from-file | --run-tests | -!(-*)f)
            _filedir
            return
            ;;
        -!(-*)L)
            _filedir -d
            return
            ;;
    esac

    ((cword > 2)) &&
        case ${words[cword - 2]} in
            --arg | --argjson)
                return
                ;;
            --slurpfile | --argfile)
                _filedir json
                return
                ;;
        esac

    if [[ $cur == -* ]]; then
        # Get jq's --help output and see whether it mentions --help
        # jq's --help only shows some of its command-line options; some are not
        # even listed in the man page!
        local help_output=$("$1" --help 2>/dev/null)

        if [[ $help_output == *--help* ]]; then
            # If the output of --help seems complete, use it
            COMPREPLY=($(compgen -W \
                '$(printf "%s" "$help_output" | _parse_help -)' -- "$cur"))
        else
            # Otherwise, use a hard-coded list of known flags, some of which do
            # not appear in the output of --help as of jq 1.6.
            COMPREPLY=($(compgen -W '--version --seq --stream --slurp
                --raw-input --null-input --compact-output --tab --indent
                --color-output -monochrome-output --ascii-output --unbuffered
                --sort-keys --raw-output --join-output --from-file --exit-status
                --arg --argjson --slurpfile --rawfile --argfile --args
                --jsonargs --run-tests --help' -- "$cur"))
        fi
        return
    fi

    local word
    for word in "${words[@]}"; do
        [[ $word != --?(json)args ]] || return
    done

    local args
    # TODO: DTRT with args taking 2 options
    # -f|--from-file are not counted here because they supply the filter
    _count_args "" "@(--arg|--arg?(json|file)|--slurpfile|--indent|--run-tests|-!(-*)L)"

    # 1st arg is filter
    ((args == 1)) && return
    # 2... are input files
    _filedir json

} &&
    complete -F _jq jq

# ex: filetype=sh
